package com.mars.framework.aspect;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author 程序员Mars
 */
public class BaseSpELAspect {

    private static final Logger log = LoggerFactory.getLogger(BaseSpELAspect.class);

    public BaseSpELAspect() {
    }

    /**
     * getValueBySpEL
     *
     * @param key            key
     * @param parameterNames parameterNames
     * @param values         values
     * @param keyConstant    keyConstant
     * @return List<String>
     */
    @SuppressWarnings("all")
    public List<String> getValueBySpEL(String key, String[] parameterNames, Object[] values, String keyConstant) {
        List<String> keys = new ArrayList<>();
        if (!key.contains("#")) {
            String s = "redis:lock:" + key + keyConstant;
            log.debug("lockKey:" + s);
            keys.add(s);
            return keys;
        } else {
            ExpressionParser parser = new SpelExpressionParser();
            EvaluationContext context = new StandardEvaluationContext();

            for (int i = 0; i < parameterNames.length; ++i) {
                context.setVariable(parameterNames[i], values[i]);
            }

            Expression expression = parser.parseExpression(key);
            Object value = expression.getValue(context);
            if (value != null) {
                if (value instanceof List) {
                    List value1 = (List) value;
                    Iterator var11 = value1.iterator();

                    while (var11.hasNext()) {
                        Object o = var11.next();
                        this.addKeys(keys, o, keyConstant);
                    }
                } else if (value.getClass().isArray()) {
                    Object[] obj = (Object[]) ((Object[]) value);
                    Object[] var18 = obj;
                    int var19 = obj.length;

                    for (int var13 = 0; var13 < var19; ++var13) {
                        Object o = var18[var13];
                        this.addKeys(keys, o, keyConstant);
                    }
                } else {
                    this.addKeys(keys, value, keyConstant);
                }
            }
            return keys;
        }
    }

    private void addKeys(List<String> keys, Object o, String keyConstant) {
        keys.add("redis:lock:" + o.toString() + keyConstant);
    }
}
